package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.vo.MemberVO;
import com.itheima.service.MemberService;
import com.itheima.utils.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 后台会员管理
 */
@RestController
@RequestMapping("/member_backend")
public class MemberController {

    @Reference
    MemberService memberService;

    /**
     * 会员信息分页查询
     *
     * @param queryPageBean
     * @return
     */
    @RequestMapping("/findByPage.do")
    public PageResult findByPage(@RequestBody QueryPageBean queryPageBean) {
        return memberService.findByPage(queryPageBean);
    }

    /**
     * 添加会员
     *
     * @return
     */
    @RequestMapping("/add.do")
    public Result add(@RequestBody MemberVO memberVO) {
        try {
            memberService.add(memberVO);
        } catch (Exception e) {
            e.printStackTrace();
            //添加失败
            return new Result(false, MessageConstant.ADD_MEMBER_FAIL);
        }
        //添加会员成功
        return new Result(true, MessageConstant.ADD_MEMBER_SUCCESS);
    }

    /**
     * 根据id删除会员
     *
     * @param id
     * @return
     */
    @RequestMapping("/deleteById.do")
    public Result deleteById(Integer id) {
        try {
            memberService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            //删除失败
            return new Result(false, MessageConstant.DELETE_MEMBER_FAIL);
        }
        //删除会员成功
        return new Result(true, MessageConstant.DELETE_MEMBER_SUCCESS);
    }

    /**
     * 删除选中的会员
     *
     * @param memberVOs
     * @return
     */
    @RequestMapping("/deleteSelected.do")
    public Result deleteSelected(@RequestBody MemberVO[] memberVOs) {
        try {
            memberService.deleteSelected(memberVOs);
        } catch (Exception e) {
            e.printStackTrace();
            //删除失败
            return new Result(false, MessageConstant.DELETE_MEMBER_FAIL);
        }
        //删除成功
        return new Result(true, MessageConstant.DELETE_MEMBER_SUCCESS);
    }

    /**
     * 根据id查询会员信息
     *
     * @param id
     * @return
     */
    @RequestMapping("/findById.do")
    public Result findById(Integer id) {
        try {
            MemberVO memberVO = memberService.findById(id);
            //查询成功,将数据返回给页面
            return new Result(true, "会员信息查询成功!", memberVO);
        } catch (Exception e) {
            e.printStackTrace();
            //查询失败
            return new Result(false, "获取数据失败,请刷新页面重试!");
        }
    }

    /**
     * 编辑会员信息
     *
     * @param memberVO
     * @return
     */
    @RequestMapping("/edit.do")
    public Result edit(@RequestBody MemberVO memberVO) {
        try {
            memberService.edit(memberVO);
        } catch (Exception e) {
            e.printStackTrace();
            //编辑会员信息失败
            return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
        }
        //编辑会员信息成功
        return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS);
    }

    @RequestMapping("/outExcel.do")
    public Result outExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            //获取数据
            List<Map<String, Object>> list = memberService.getMemberReportData();

            //创建excel对象
            String filePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "member_template.xlsx";
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            //读取第一个工作表
            XSSFSheet sheet = excel.getSheetAt(0);
            //行
            int x = 1;

            for (Map<String, Object> map : list) {

                String fileNumber = (String) map.get("fileNumber");
                String name = (String) map.get("name");
                String sex = (String) map.get("sex");
                Integer age = (Integer) map.get("age");
                String healthManager = (String) map.get("healthManager");
                String phoneNumber = (String) map.get("phoneNumber");
                String regTime = DateUtils.parseDate2String((Date) map.get("regTime"));


                //获取第x行
                XSSFRow row = sheet.createRow(x);
                if (fileNumber != null) {
                    row.createCell(0).setCellValue(fileNumber);//档案号
                } else {
                    row.createCell(0).setCellValue("未填写");
                }
                if (name != null) {
                    row.createCell(1).setCellValue(name);//姓名
                } else {
                    row.createCell(1).setCellValue("未填写");
                }
                if (sex != null) {
                    row.createCell(2).setCellValue(sex);//性别
                } else {
                    row.createCell(2).setCellValue("未填写");
                }
                if (age != null) {
                    row.createCell(3).setCellValue(age);//年龄
                } else {
                    row.createCell(3).setCellValue("未填写");
                }
                if (healthManager != null) {
                    row.createCell(4).setCellValue(healthManager);//健康管理师
                } else {
                    row.createCell(4).setCellValue("未填写");
                }
                if (phoneNumber != null) {
                    row.createCell(5).setCellValue(phoneNumber);//手机号
                } else {
                    row.createCell(5).setCellValue("未填写");
                }
                if (regTime != null) {
                    row.createCell(6).setCellValue(regTime);//注册时间
                } else {
                    row.createCell(6).setCellValue("未填写");
                }
                x++;
            }

            ServletOutputStream os = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=MemberReport.xlsx");
            excel.write(os);
            os.flush();
            os.close();
            excel.close();

            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS);
        } catch (IOException e) {
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }
}